<script setup lang="ts">
import { ref, defineEmits, watch } from "vue"
import { $t } from '@vben/locales';
import type { FormInstance } from 'element-plus'
import { Check, X } from '@vben/icons';
import { cloneDeep } from '@vben/utils'

import { debounceFn } from "#/utils/debounce"
import { getExamListApi } from "#/api/manage/paper"
import { getCertificationInfoApi, createExamInfoApi, publishExamInfoApi, updateExamInfoApi } from "#/api/manage/examination-mgr"
import { getCertOrgByCertIdApi } from '#/api/system/orgMgr'
import { trimStringParams } from '#/utils/trimStringParams'
import { ChosePaperDialog } from "../examination-mgr"

import { configurationList } from '../const'

defineOptions({ name: 'Dialog' })

const props = defineProps({
  courseList: {
    type: Array,
    required: true
  },
  processTreeData: {
    type: Function,
    required: true
  }
});
const chosePaperDialogRef = ref<InstanceType<typeof ChosePaperDialog> | null>(null)

const examNameTxt = $t('common.inputPhTxt', [$t('exam.examNameLabel')])
const examCourseTxt = $t('common.selectPhTxt', [$t('exam.examCourseLabel')])
const certificationTxt = $t('common.selectPhTxt', [$t('exam.linkCert')])
const examClassTxt = $t('common.selectPhTxt', [$t('exam.examClassLabel')])
const examTimeTxt = $t('common.selectPhTxt', [$t('exam.examTime')])
const examDurationTxt = $t('common.inputPhTxt', [$t('exam.examDuration')])
const examDesTxt = $t('common.inputPhTxt', [$t('exam.examDes')])
const correctTypeTxt = $t('common.selectPhTxt', [$t('exam.correctType')])

const dialogVisible = ref(false)
const examType = ref('online')
const editData = ref()
const defaultForm = {
  name: '',
  courseId: null,
  certificationId: '',
  organizationIdList: null,
  beginTime: null,
  duration: null,
  location: '',
  description: '',
  paperIdList: [],
  correctMethod: null,
  configuration: {
    questionShuffle: false,
    optionShuffle: false,
    suppressSwitchingScreen: false,
    suppressSwitchingScreenCount: 3,
    suppressCopyAndPaste: false,
    suppressCopyAndPasteCount: 3,
    deviceCheck: false,
    // monitor: false,
    // faceDetect: false,
    // aiAnalysis: false
  }
}
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const saveLoading = ref(false)
const certLoading = ref(false)
const certOrgLoading = ref(false)
const examForm = ref(cloneDeep(defaultForm))
const certificationList = ref<any>([])
const orgTreeList = ref<any>([])
const defaultPaperList = ref<any>([])
const paperIdListSelected = ref<any>([])
const rules = {
  name: [
    { required: true, message: examNameTxt, trigger: 'blur' },
  ],
  courseId: [
    { required: true, message: examCourseTxt, trigger: 'change' }
  ],
  certificationId: [
    { required: true, message: certificationTxt, trigger: 'change' }
  ],
  organizationIdList: [
    { required: true, message: examClassTxt, trigger: 'change' }
  ],
  beginTime: [
    { required: true, message: examTimeTxt, trigger: 'change' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          const selectedTime = new Date(value)
          const currentTime = new Date()
          if (selectedTime <= currentTime) {
            callback(new Error($t('exam.examTimeAfterTxt')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  duration: [
    { required: true, message: examDurationTxt, trigger: 'change' }
  ],
  description: [
    { required: true, message: examDesTxt, trigger: 'blur' }
  ],
  paperIdList: [
    { required: true, message: $t('common.selectPhTxt', [$t('paper.paperTxt')]), trigger: 'change' }
  ],
  correctMethod: [
    { required: true, message: correctTypeTxt, trigger: 'change' }
  ],
  'configuration.suppressCopyAndPasteCount': [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (examForm.value.configuration.suppressCopyAndPaste && (!value || value < 1)) {
          callback(new Error($t('common.inputPhTxt', [$t('exam.limitTimesTxt')])))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  'configuration.suppressSwitchingScreenCount': [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (examForm.value.configuration.suppressSwitchingScreen && (!value || value < 1)) {
          callback(new Error($t('common.inputPhTxt', [$t('exam.limitTimesTxt')])))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
}

const emit = defineEmits(['updateList']);
const handleClose = () => {
  examForm.value = cloneDeep(defaultForm)
  formRef.value?.resetFields()
  editData.value = null
  certificationList.value = []
  orgTreeList.value = []
  paperIdListSelected.value = []
  dialogVisible.value = false
}

const submit = debounceFn((type: any) => {
  if (!formRef) return
  formRef.value?.validate((valid) => {
    if (valid) {
      const trimParams = trimStringParams(examForm.value)
      const params = {
        mode: examType.value,
        configuration: examForm.value.configuration
      } as any
      Object.keys(trimParams).forEach(key => {
        const kVal = trimParams[key as keyof typeof trimParams]
        if (kVal) {
          if (key === 'organizationIdList') {
            params[key] = [kVal]
          }
          else {
            params[key] = kVal
          }
        }
      })
      if (type == 'SAVE') {
        saveLoading.value = true
      } else {
        submitLoading.value = true
      }
      let Api = null
      if (editData.value) params['id'] = editData.value.id
      if (type == 'PUBLISH') {
        Api = publishExamInfoApi(trimStringParams(params))
      } else {
        Api = editData.value ? updateExamInfoApi(trimStringParams(params)) : createExamInfoApi(trimStringParams(params))
      }
      Api.then(() => {
        handleClose()
        emit('updateList')
      }).catch((err) => {
        console.log(err)
      }).finally(() => {
        if (type == 'SAVE') {
          saveLoading.value = false
        } else {
          submitLoading.value = false
        }
      })
    }
  })
}, 300, true)

const cancelClick = () => {
  handleClose()
}

const getDefaultPaper = (ids: any) => {
  let params = {
    certificationIdList: ids
  }
  getExamListApi(params).then((res) => {
    const { data } = res
    defaultPaperList.value = data ?? []
    paperIdListSelected.value = data.filter((_: { id: any }) => examForm.value.paperIdList.find(id => id === _?.id))
    console.log('examForm.value.paperIdList')
    console.log(examForm.value.paperIdList)
  }).finally(() => { })
}

const setEditData = (data: any) => {
  editData.value = data
  const {
    name,
    courseId,
    certificationId,
    organizationIdList,
    beginTime,
    duration,
    location,
    description,
    paperIdList = [],
    correctMethod,
    configuration
  } = data.draft ?? data
  const orgId = organizationIdList ? organizationIdList?.join() : ''
  examForm.value = {
    name,
    courseId,
    certificationId,
    organizationIdList: orgId,
    beginTime,
    duration,
    location,
    description,
    paperIdList,
    correctMethod,
    configuration
  }
  getCertificationList(courseId)
  getCertOrgList(certificationId, orgId)
  getDefaultPaper(certificationId)
}

const inint = (type: any, data: any) => {
  examType.value = type ?? 'online'
  if (data) {
    setEditData(data)
  }
  dialogVisible.value = true
}
const getCertificationList = (id: any) => {
  const params = { courseIdList: id };
  certLoading.value = true
  getCertificationInfoApi(params).then((res) => {
    let { data = [] } = res;
    certificationList.value = data;
  }).finally(() => {
    certLoading.value = false;
  })
}

const getCertOrgList = (certId: any, orgId: any) => {
  let params = {
    certId,
    orgId
  }
  certOrgLoading.value = true
  getCertOrgByCertIdApi(params).then((res) => {
    // 递归处理返回的树型数据
    orgTreeList.value = props.processTreeData(res || [])
  }).finally(() => {
    certOrgLoading.value = false
  })
}

const courseUpdate = (data: any) => {
  examForm.value.certificationId = ''
  examForm.value.organizationIdList = null
  certificationList.value = []
  orgTreeList.value = []
  examForm.value.paperIdList = []
  if (data) {
    getCertificationList(data)
  }
}
const certUpdate = (data: any) => {
  examForm.value.organizationIdList = null
  orgTreeList.value = []
  examForm.value.paperIdList = []
  if (data) {
    getCertOrgList(data, null)
  }
}
const orgListUpdate = (data: any) => {
  console.log('选择的组织ID:', data)
  // 可以在这里添加选择组织后的逻辑处理
}

const addPaper = () => {
  chosePaperDialogRef.value?.inint(examForm.value.paperIdList)
}

const choseExamType = (data: any) => {
  paperIdListSelected.value = data
  examForm.value.paperIdList = data.map((item: { papersId: any }) => {
    return item.papersId
  })
  if (data?.length > 0) {
    formRef.value?.clearValidate(['paperIdList'])
  } else {
    formRef.value?.validateField(['paperIdList'])
  }
}

const disabledDate = (time: any) => {
  // 获取当天0点的时间戳
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const todayStartTime = today.getTime()

  // 比较时间是否小于当天0点
  return time.getTime() < todayStartTime
}

watch(dialogVisible, () => {
  if (dialogVisible) {
  }
})



// 同步根级别字段和 configuration 对象
watch(() => examForm.value.configuration.suppressSwitchingScreenCount, (newVal) => {
  if (examForm.value.configuration) {
    examForm.value.configuration.suppressSwitchingScreenCount = newVal
  }
})

watch(() => examForm.value.configuration.suppressCopyAndPasteCount, (newVal) => {
  if (examForm.value.configuration) {
    examForm.value.configuration.suppressCopyAndPasteCount = newVal
  }
})

defineExpose({ inint })

</script>
<template>
  <el-drawer :close-on-click-modal="false" :close-on-press-escape="false" :append-to-body="true" size="70%"
    v-model="dialogVisible" direction="rtl" @close="handleClose">
    <template #header>
      <h4 class="text-black font-bold">{{ $t(editData ? 'common.editTxt' : 'common.newTxt', [$t(`exam.${examType}`)]) }}
      </h4>
    </template>
    <template #default>
      <div class="flex h-full flex-col">
        <div class="text-[14px] text-[#191919] leading-[22px] font-bold mb-[16px]">{{ $t('exam.examInfo') }}</div>
        <el-form ref="formRef" class="w-[100%]" :inline="true" :model="examForm" :rules="rules" label-width="116px"
          label-position="right">
          <el-form-item :label="$t('exam.examNameLabel')" prop="name" style="width: 50%;" required>
            <el-input clearable type="text" :maxlength="100" class="w-[100%]" v-model="examForm.name"
              :placeholder="examNameTxt"></el-input>
          </el-form-item>
          <el-form-item :label="$t('exam.examCourseLabel')" prop="courseId" style="width: 50%;" required>
            <el-select clearable v-model="examForm.courseId" :placeholder="examCourseTxt" @change="courseUpdate">
              <el-option v-for="item in props.courseList as any" :key="item?.id" :label="item?.name"
                :value="item?.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('exam.linkCert')" prop="certificationId" style="width: 50%;" required>
            <el-select :loading="certLoading" clearable v-model="examForm.certificationId" @change="certUpdate"
              :placeholder="certificationTxt">
              <el-option v-for="item in certificationList" :key="item?.id" :label="item?.name"
                :value="item?.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('exam.examClassLabel')" prop="organizationIdList" style="width: 50%;" required>
            <el-cascader :loading="certOrgLoading" clearable :show-all-levels="false" class="w-full"
              v-model="examForm.organizationIdList" :placeholder="examClassTxt" :options="orgTreeList"
              @change="orgListUpdate"
              :props="{ emitPath: false, checkStrictly: true, multiple: false, label: 'name', value: 'orgId', children: 'children' }" />
          </el-form-item>
          <el-form-item :label="$t('exam.examTime')" prop="beginTime" style="width: 50%;" required>
            <el-date-picker format="YYYY-MM-DD HH:mm:ss" time-format="HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="new Date()" style="width:100%" v-model="examForm.beginTime" type="datetime"
              :placeholder="examTimeTxt" :disabled-date="disabledDate" />
          </el-form-item>
          <el-form-item :label="$t('exam.examDuration')" prop="duration" style="width: 50%;" required>
            <el-input-number :controls="false" :min="0" :max="10000" class="w-[100%]" v-model="examForm.duration"
              :placeholder="examDurationTxt">
              <template #suffix>
                <span>{{ $t('exam.minutesTxt') }}</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item :label="$t('exam.examPlace')" prop="location" style="width: 100%;">
            <el-input clearable type="text" :maxlength="200" class="w-[100%]" v-model="examForm.location"
              :placeholder="$t('common.inputPhTxt', [$t('exam.examPlace')])"></el-input>
          </el-form-item>
          <el-form-item :label="$t('exam.examDes')" prop="description" style="width: 100%;" required>
            <el-input type="textarea" :maxlength="1000" class="w-[100%]" v-model="examForm.description"
              :placeholder="examDesTxt"></el-input>
          </el-form-item>
          <div class="border-b border-color:#DCDFE6 pt-[24px] mb-[24px]"></div>
          <el-form-item :label="$t('exam.chosePaper')" prop="paperIdList" style="width: 100%;" required>
            <!-- v-if="examForm.paperIdList.length === 0" -->
            <div v-if="examForm.paperIdList.length === 0 || paperIdListSelected.length === 0"
              class="flex items-center w-full bg-[#0067d11a] pr-[5px] pl-[10px] rounded-[4px]">
              <span>{{ $t('common.clickTxt') }}</span>
              <el-button :disabled="!examForm.certificationId" link type="primary" @click="addPaper">{{
                $t('exam.selectPaper')
                }}</el-button>
            </div>
            <div v-else>
              <div @click="addPaper" class="text-[#0067D1] cursor-pointer"
                v-for="(paper, index) in paperIdListSelected as any" :key="index">
                <div>{{ paper?.papersName ?? '--' }}</div>
              </div>
            </div>
          </el-form-item>
          <el-form-item :label="$t('exam.correctType')" prop="correctMethod" style="width: 100%;" required>
            <el-radio-group v-model="examForm.correctMethod">
              <el-radio value="allManual">{{ $t('exam.allHandleCorrect') }}</el-radio>
              <el-radio value="subjectivityManual">{{ $t('exam.subjectCorrect') }}</el-radio>
              <el-radio value="allAI">{{ $t('exam.aiCorrect') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label=" " style="width: 100%;">
            <div v-for="(item, index) in configurationList" :key="index"
              class="w-[50%] flex justify-start items-center pr-[50px]">
              <div class="w-[90px] text-right" :style="{ color: item.disabled ? '#e4e4e7' : 'inhert' }">{{
                item.configTxt
                }}</div>
              <el-switch :disabled="item.disabled" v-model="examForm.configuration[item.key]" style="margin-left: 24px"
                inline-prompt :active-icon="Check" :inactive-icon="X" />
              <div class="ml-[10px] flex items-center"
                v-if="item.countKey && item.setTimes && examForm.configuration[item.key]">
                <span>{{ $t('exam.limitTimesTxt') }}</span>
                <el-form-item :prop="`configuration.${item.countKey}`" style="margin: 0; width: auto;">
                  <el-input-number :controls="false" :min="1" :max="1000" v-model="examForm.configuration[item.countKey]"
                    class="w-[60px] ml-[10px]"></el-input-number>
                    <span class="ml-[10px]">{{ $t('exam.timesTxt') }}</span>
                </el-form-item>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">{{ $t('common.cancelTxt') }}</el-button>
        <el-button :loading="saveLoading" @click="submit('SAVE')">{{ $t('common.saveTxt') }}</el-button>
        <el-button :loading="submitLoading" type="primary" @click="submit('PUBLISH')">{{ $t('common.pushTxt') }}</el-button>
      </div>
    </template>
  </el-drawer>
  <ChosePaperDialog ref="chosePaperDialogRef" :certificationId="examForm.certificationId"
    :paperIdList="examForm.paperIdList" @choseExamType="choseExamType">
  </ChosePaperDialog>
</template>
<style lang="scss" scoped>
:deep(.el-form--inline .el-form-item) {
  margin-right: 0px;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-radio__label) {
  font-weight: 400;
}
</style>
